package com.fayou.cloud.seataorderservice2001.service.impl;

import com.fayou.cloud.seataorderservice2001.entity.OrderTbl;
import com.fayou.cloud.seataorderservice2001.dao.OrderTblDao;
import com.fayou.cloud.seataorderservice2001.feign.StorageFeignClient;
import com.fayou.cloud.seataorderservice2001.service.OrderTblService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * (OrderTbl)表服务实现类
 *
 * @author makejava
 * @since 2020-06-03 16:18:54
 */
@Service("orderTblService")
public class OrderTblServiceImpl implements OrderTblService {
    @Resource
    private OrderTblDao orderTblDao;

//    @Resource
//    private StorageFeignClient storageFeignClient;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public OrderTbl queryById(Integer id) {
        return this.orderTblDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<OrderTbl> queryAllByLimit(int offset, int limit) {
        return this.orderTblDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param orderTbl 实例对象
     * @return 实例对象
     */
    @Override
    public OrderTbl insert(OrderTbl orderTbl) {
        this.orderTblDao.insert(orderTbl);
        return orderTbl;
    }

    /**
     * 修改数据
     *
     * @param orderTbl 实例对象
     * @return 实例对象
     */
    @Override
    public OrderTbl update(OrderTbl orderTbl) {
        this.orderTblDao.update(orderTbl);
        return this.queryById(orderTbl.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.orderTblDao.deleteById(id) > 0;
    }

    /**
     * 下单：创建订单、减库存，涉及到两个服务
     *
     * @param userId
     * @param commodityCode
     * @param count
     */
    @GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void placeOrder(String userId, String commodityCode, Integer count) {
////        BigDecimal orderMoney = new BigDecimal(count).multiply(new BigDecimal(5));
//        OrderTbl order = new OrderTbl()
//                .setUserId(userId)
//                .setCommodityCode(commodityCode)
//                .setCount(count)
//                .setMoney(100*count);
//        orderTblDao.insert(order);
//        storageFeignClient.deduct(commodityCode, count);
//
    }

}